# frozen_string_literal: true

module QA
  RSpec.describe 'Govern', :skip_live_env, product_group: :threat_insights do
    describe 'Vulnerability report in a project' do
      let!(:project) do
        Resource::Project.fabricate_via_api! do |project|
          project.name = 'project-export-vulnerability-report'
          project.description = 'Project to check export vulnerability report feature'
          project.initialize_with_readme = true
        end
      end

      let(:vuln_severity) { :HIGH }

      let(:download_dir) { QA::Runtime::Env.chrome_default_download_path }

      let(:vulnerabilities) do
        { "Elves vulnerability": "Pale skin and pointy ears",
          "Dwarves vulnerability": "Short, but stern and tough",
          "Men vulnerability": "Good and bad, greedy and selfless",
          "Orcs vulnerability": "Faithful to the dark lord",
          "CVE-2017-18269 in glibc": "Short description to match in specs" }
      end

      let!(:vulnerability_report) do
        vulnerabilities.each do |name, description|
          QA::EE::Resource::VulnerabilityItem.fabricate_via_api! do |vulnerability|
            vulnerability.id = project.id
            vulnerability.severity = vuln_severity
            vulnerability.name = name
            vulnerability.description = description
          end
        end
      end

      let(:vulnerability_name) { "CVE-2017-18269 in glibc" }
      let(:vulnerability_description) { "Short description to match in specs" }

      before do
        Flow::Login.sign_in
        project.visit!
      end

      it 'can export vulnerability report to csv',
         testcase: 'https://gitlab.com/gitlab-org/gitlab/-/quality/test_cases/384370' do
        Page::Project::Menu.perform(&:go_to_vulnerability_report)

        EE::Page::Project::Secure::SecurityDashboard.perform do |security_dashboard|
          expect(security_dashboard).to have_vulnerability(description: vulnerability_name)
          security_dashboard.export_vulnerabilities_to_csv
        end
        file_name = get_exported_csv_filename
        validate_csv(file_name)
      end

      def get_exported_csv_filename
        csv_file = nil
        file_name_glob = "#{project.full_path.split('/').join('-')}_vulnerabilities"
        Support::Waiter.wait_until(max_duration: 20, sleep_interval: 1,
                                   message: "Waiting for vulnerabilities csv export") do
          csv_file = Dir["#{download_dir}/*"].find { |file| file =~ /#{file_name_glob}.*csv/ }
        end

        csv_file
      end

      def validate_csv(file_name)
        vulnerabilities_from_csv = []
        CSV.foreach(file_name, headers: true) do |row|
          vulnerabilities_from_csv << [row['Vulnerability'], row['Details']]
        end
        expect(vulnerabilities.stringify_keys.to_a).to match_array vulnerabilities_from_csv
      end
    end
  end
end
